package com.brillilab.service.logic.recycle;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.brillilab.common.entity.PageVo;
import com.brillilab.common.entity.ResponseVo;
import com.brillilab.domain.enums.common.BoolEnum;
import com.brillilab.domain.enums.kit.KitEnum;
import com.brillilab.domain.po.kit.Kit;
import com.brillilab.domain.po.kit.Reagent;
import com.brillilab.domain.vo.kit.RecycleKitVo;
import com.brillilab.service.core.kit.IKitService;
import com.brillilab.service.core.kit.IReagentService;
import com.brillilab.service.core.kit.IReagentTypeService;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 回收站
 * @author wmh
 */
@Service
@Transactional
public class RecycleLogic {

    @Resource
    private IKitService iKitService;
    @Resource
    private IReagentTypeService reagentTypeService;
    @Resource
    private IReagentService reagentService;

    /**
     * 删除试剂列表
     * @param pageNum
     * @param pageSize
     * @return
     */
    public PageVo<RecycleKitVo> getKitRecyclePage(Integer pageNum,Integer pageSize,Long labId) {

        PageHelper.startPage(pageNum > 0 ? pageNum : 1,pageSize > 0 ? pageSize : 10);
        List<RecycleKitVo> kits=iKitService.selectByIsDelete(labId,KitEnum.IsDelete.YES.getValue());
        //firstReagentTypeId
        List<Long> reagentTypeId=kits.stream().map(RecycleKitVo::getReagentTypeId).distinct().collect(Collectors.toList());
        Map<Long, Long> firstReagentTypeMap=reagentTypeService.selectFirstReagentTypeMap(reagentTypeId);
        kits.forEach(e -> {
            e.setFirstReagentTypeId(firstReagentTypeMap.get(e.getReagentTypeId()));
            e.setKitType(e.getClassify().equals(KitEnum.Classify.REAGENT.getValue()) ? e.getKitType() : KitEnum.Classify.SAMPLE.getValue());
        });

        return new PageVo<>(kits);
    }

    /**
     * 恢复删除的试剂
     * @param kitId
     * @return
     */
    public boolean kitRecovery(Long labId,Long kitId) {
        Kit kit=iKitService.selectById(kitId);
        Assert.isTrue(kit!=null,"试剂不存在！");
        Assert.isTrue(labId.equals(kit.getLabId()),"试剂不是该实验室试剂！");
        kit.setIsDelete(0);
        iKitService.updateById(kit);

        List<Reagent> reagents=reagentService.selectListAllState(kitId);
        reagents.forEach(e -> e.setIsDelete(BoolEnum.FALSE.getValue()));
        reagentService.updateBatch(reagents);

        return true;
    }
}
